import tensorflow as tf

# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")
tf.summary.scalar('state', state)  # 添加值监听

# 创建一个 op, 其作用是使 state 增加 1

one = tf.constant(1)
tf.summary.scalar('one', one)

new_value = tf.add(state, one)
update = tf.assign(state, new_value)
tf.summary.scalar('update', update)

node1 = tf.constant(3.0, dtype=tf.float32, name='node1')  # 声明会话内常量
tf.summary.scalar('node1', node1)

node2 = tf.constant(4, dtype=tf.float32)  # 强制类型
tf.summary.scalar('node2', node2)
print(node1, node2)

node3 = tf.add(node1, node2, name="node3")
tf.summary.scalar('node3', node3)
print("node3: ", node3)

# 占位符
a = tf.placeholder(tf.float32, name="a")
b = tf.placeholder(tf.float32, name="b")
adder_node = a + b
add_and_triple = adder_node * 3.  # 测试进一步计算

WW = tf.Variable([.3], dtype=tf.float32, name='WW')
bb = tf.Variable([-.3], dtype=tf.float32, name="bb")
xx = tf.placeholder(tf.float32, name='xx')
linear_model = WW * xx + bb

yy = tf.placeholder(tf.float32)  # yy模拟提供的目标值
# 定义损失函数为各值相差的平方和
squared_deltas = tf.square(linear_model - yy)
loss = tf.reduce_sum(squared_deltas)

# 测试人为修改修改变量值使损失函数最小化
fixWW = tf.assign(WW, [-1.], name='fixWW')
fixbb = tf.assign(bb, [1.], name='fixbb')

sess = tf.InteractiveSession()  # 创建会话

merged = tf.summary.merge_all()  # 获取全部张量的操作
log_writer = tf.summary.FileWriter('data_log/l008', sess.graph)

# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.global_variables_initializer()

# 启动图, 运行 op
# 运行 'init' op
sess.run(init_op)

# 打印 'state' 的初始值
print(sess.run(state))
# 运行 op, 更新 'state', 并打印 'state'
for _ in range(3):
    sess.run(update)
    print(sess.run(state))
print(sess.run([node1, node2]))  # 得到最后的预期值[3.0, 4]
print("sess.run(node3): ", sess.run(node3))  # 节点间计算

print(sess.run(adder_node, {a: 3, b: 4.5}))
print(sess.run(adder_node, {a: [1, 3], b: [2, 4]}))  # 依次计算1+2、3+4，以此类推
print(sess.run(add_and_triple, {a: 3, b: 4.5}))

print(sess.run(WW))
print(sess.run(linear_model, {xx: [1, 2, 3, 4]}))  # linear_model依次计算：0.3 * 1 + (-0.3) 、 0.3 * 2 + (-0.3) 、 0.3 * 3 + (-0.3) 、 0.3 * 4 + (-0.3)

print(sess.run(loss, {xx: [1, 2, 3, 4], yy: [0, -1, -2, -3]}))  # 获取损失函数值

# 进行变量赋值，然后重新计算损失函数值
sess.run([fixWW, fixbb])
print(sess.run(loss, {xx: [1, 2, 3, 4], yy: [0, -1, -2, -3]}))

summary = sess.run(merged)
log_writer.add_summary(summary)

sess.close()

# 输出:

# 0
# 1
# 2
# 3
log_writer.close()
